package com.xie.o2o.controller.shopadmin;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sun.org.apache.bcel.internal.classfile.Unknown;
import com.xie.o2o.dto.ShopExecution;
import com.xie.o2o.entity.Area;
import com.xie.o2o.entity.PersonInfo;
import com.xie.o2o.entity.Shop;
import com.xie.o2o.entity.ShopCategory;
import com.xie.o2o.enums.ShopStateEnum;
import com.xie.o2o.service.AreaService;
import com.xie.o2o.service.ShopCategoryService;
import com.xie.o2o.service.ShopService;
import com.xie.o2o.util.CodeUtil;
import com.xie.o2o.util.HttpServletUtil;
import com.xie.o2o.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @create: xie
 */
@Controller
@RequestMapping("/shopadmin")
public class ShopManagementController {
    @Autowired
    private ShopCategoryService shopCategoryService;
    @Autowired
    private AreaService areaService;
    @Autowired
    private ShopService shopService;

    /**
     * 店铺管理选项，判断是否有权限，没有权限转发回shoplist
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getshopmanagementinfo", method = RequestMethod.GET)
    @ResponseBody
    private Map<String, Object> getShopManagementInfo(HttpServletRequest request) {
        Map<String, Object> modelMap = new HashMap<String, Object>();
        long shopId = HttpServletUtil.getLong(request, "shopId");
        if (shopId <= 0) {
            Object currentShopObj = request.getSession().getAttribute("currentShop");
            if (currentShopObj == null) {
                modelMap.put("redirect", true);
                modelMap.put("url", "/mvcoto/shopadmin/shoplist");
            } else {
                Shop currentShop = (Shop) currentShopObj;
                modelMap.put("redirect", false);
                modelMap.put("shopId", currentShop.getShopId());
            }
        } else {
            Shop currentShop = new Shop();
            currentShop.setShopId(shopId);
            request.getSession().setAttribute("currentShop", currentShop);
            modelMap.put("redirect", false);
        }
        return modelMap;
    }

    /**
     * 用户id下的店铺列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getshoplist", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getShopList(HttpServletRequest request) {
        Map<String, Object> modelMap = Maps.newHashMap();
        PersonInfo user = (PersonInfo) request.getSession().getAttribute("user");
        try {
            Shop shop = new Shop();
            shop.setOwner(user);
            ShopExecution se = shopService.getShopList(shop, 0, 100);
            modelMap.put("shopList", se.getShopList());
            // 列出店铺成功之后，将店铺放入session中在拦截器里作权限验证依据，即该帐号只能操作它自己的店铺
            request.getSession().setAttribute("shopList", se.getShopList());
            modelMap.put("user", user);
            modelMap.put("success", true);
        } catch (Exception e) {
            modelMap.put("success", false);
            modelMap.put("errMsg", e.getMessage());
        }
        return modelMap;
    }

    /**
     * 获取被修改店铺信息
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getshopbyid", method = RequestMethod.GET)
    public Map<String, Object> getShopById(HttpServletRequest request) {
        Map<String, Object> map = Maps.newHashMap();
        List<Area> areaList = null;
        Long shopId = HttpServletUtil.getLong(request, "shopId");
        if (shopId > -1) {
            Shop shop = shopService.getByShopId(shopId);
            try {
                areaList = areaService.getAreaList();
                map.put("success", true);
                map.put("shop", shop);
                map.put("areaList", areaList);
            } catch (Exception e) {
                e.printStackTrace();
                map.put("success", false);
                map.put("errMsg", e.getMessage());
            }
        } else {
            map.put("success", false);
            map.put("errMsg", "shopid为空");
        }
        return map;
    }

    /**
     * 修改店铺信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/modifyshop", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> modifyShop(HttpServletRequest request) {
        Map<String, Object> map = Maps.newHashMap();
        String shopStr = HttpServletUtil.getString(request, "shopStr");
        ObjectMapper mapper = new ObjectMapper();
        //获取数据
        Shop shop = null;
        try {
            shop = mapper.readValue(shopStr, Shop.class);
        } catch (IOException e) {
            e.printStackTrace();
            map.put("success", false);
            map.put("errMsg", e.getMessage());
            return map;
        }
        //获取店铺图片
        MultipartFile shopImg = ((MultipartHttpServletRequest) request).getFile("shopImg");
        //修改店铺信息
        if (shop != null && shop.getShopId() != null) {
            ShopExecution shopExecution = null;
            //没有新的图片就不传入
            if (shopImg == null) {
                shopExecution = shopService.modifyShop(shop, null);
            } else {
                //有新的图片就替换
                shopExecution = shopService.modifyShop(shop, shopImg);
            }

            if (shopExecution.getState() == ShopStateEnum.SUCCESS.getState()) {
                map.put("success", true);
            } else {
                map.put("success", false);
                map.put("errMsg", shopExecution.getStateInfo());
            }
        } else {
            map.put("success", false);
            map.put("errMsg", "请输入店铺id");
            return map;
        }
        return map;
    }

    /**
     * 注册店铺
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/registershop", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> registerShop(HttpServletRequest request) {
        Map<String, Object> map = Maps.newHashMap();
        MultipartFile shopImg = null;
        String shopStr = HttpServletUtil.getString(request, "shopStr");
        //获取登录用户信息
        PersonInfo personInfo=(PersonInfo) request.getSession().getAttribute("user");
        //获取注册店铺数据
        Shop shop = JsonUtil.string2Obj(shopStr, Shop.class);
        //获取店铺图片
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        if (commonsMultipartResolver.isMultipart(request)) {
            //图片存在
            shopImg = ((MultipartHttpServletRequest) request).getFile("shopImg");
        } else {
            //图片不存在
            map.put("success", false);
            map.put("errMsg", "上传图片不能为空");
            return map;
        }
        //注册店铺
        if (shop != null && shopImg != null) {
            //店铺信息和图片都不为空
            //设置店主为当前用户
            shop.setOwner(personInfo);
            ShopExecution shopExecution = shopService.addShop(shop, shopImg);
            if (shopExecution.getState() == ShopStateEnum.CHECK.getState()) {
                map.put("success", true);
                //店铺注册成功之后。实时添加到shopList做拦截器权限校验，避免操作错乱
                @SuppressWarnings("unchecked")
                List<Shop> shopList = (List<Shop>) request.getSession().getAttribute("shopList");
                if (shopList == null) {
                    shopList = Lists.newArrayList();
                }
                shopList.add(shopExecution.getShop());
                request.getSession().setAttribute("shopList", shopList);
            } else {
                map.put("success", false);
                map.put("errMsg", shopExecution.getStateInfo());
            }
        } else {
            map.put("success", false);
            map.put("errMsg", "店铺信息不能为空");
            return map;
        }
        return map;
    }

    /**
     * 注册店铺初始化数据
     *
     * @return
     */
    @RequestMapping("/getshopinitinfo")
    @ResponseBody
    public Map<String, Object> getshopinitinfo() {
        Map<String, Object> map = Maps.newHashMap();
        List<Area> areaList = areaService.getAreaList();
        List<ShopCategory> shopCategoryList = shopCategoryService.getShopCategoryList(new ShopCategory());
        map.put("success", true);
        map.put("shopCategoryList", shopCategoryList);
        map.put("areaList", areaList);
        return map;
    }
}
